<template>
  <div class="system-settings">
    <el-row :gutter="20">
      <!-- 系统信息 -->
      <el-col :span="12">
        <el-card class="system-info-card">
          <template #header>
            <div class="card-header">
              <span>系统信息</span>
              <el-button type="primary" size="small" @click="refreshSystemInfo">
                <el-icon><Refresh /></el-icon>
                刷新
              </el-button>
            </div>
          </template>

          <div class="info-section">
            <h4>应用信息</h4>
            <div class="info-list">
              <div class="info-item">
                <span class="label">应用名称:</span>
                <span class="value">{{ systemInfo.application?.name || '-' }}</span>
              </div>
              <div class="info-item">
                <span class="label">版本:</span>
                <span class="value">{{ systemInfo.application?.version || '-' }}</span>
              </div>
              <div class="info-item">
                <span class="label">描述:</span>
                <span class="value">{{ systemInfo.application?.description || '-' }}</span>
              </div>
            </div>
          </div>

          <el-divider />

          <div class="info-section">
            <h4>系统环境</h4>
            <div class="info-list">
              <div class="info-item">
                <span class="label">操作系统:</span>
                <span class="value">{{ systemInfo.system?.platform || '-' }}</span>
              </div>
              <div class="info-item">
                <span class="label">Python版本:</span>
                <span class="value">{{ getPythonVersion() }}</span>
              </div>
              <div class="info-item">
                <span class="label">Django版本:</span>
                <span class="value">{{ systemInfo.system?.django_version || '-' }}</span>
              </div>
              <div class="info-item">
                <span class="label">调试模式:</span>
                <el-tag :type="systemInfo.system?.debug_mode ? 'warning' : 'success'">
                  {{ systemInfo.system?.debug_mode ? '开启' : '关闭' }}
                </el-tag>
              </div>
            </div>
          </div>

          <el-divider />

          <div class="info-section">
            <h4>数据库信息</h4>
            <div class="info-list">
              <div class="info-item">
                <span class="label">数据库引擎:</span>
                <span class="value">{{ getDatabaseEngine() }}</span>
              </div>
              <div class="info-item">
                <span class="label">数据库名称:</span>
                <span class="value">{{ systemInfo.database?.name || '-' }}</span>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>

      <!-- 用户统计 -->
      <el-col :span="12">
        <el-card class="user-stats-card">
          <template #header>
            <span>用户统计</span>
          </template>

          <div class="stats-overview">
            <el-row :gutter="20">
              <el-col :span="8">
                <div class="stat-item">
                  <div class="stat-number">{{ userStats.total_users || 0 }}</div>
                  <div class="stat-label">总用户数</div>
                </div>
              </el-col>
              <el-col :span="8">
                <div class="stat-item">
                  <div class="stat-number">{{ userStats.active_users || 0 }}</div>
                  <div class="stat-label">活跃用户</div>
                </div>
              </el-col>
              <el-col :span="8">
                <div class="stat-item">
                  <div class="stat-number">{{ userStats.inactive_users || 0 }}</div>
                  <div class="stat-label">禁用用户</div>
                </div>
              </el-col>
            </el-row>
          </div>

          <el-divider />

          <div class="role-stats">
            <h4>按角色统计</h4>
            <div class="role-list">
              <div v-for="(count, role) in userStats.by_role" :key="role" class="role-item">
                <span class="role-name">{{ getRoleText(role) }}:</span>
                <el-tag :type="getRoleType(role)">{{ count }} 人</el-tag>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" style="margin-top: 20px;">
      <!-- 学生统计 -->
      <el-col :span="12">
        <el-card class="student-stats-card">
          <template #header>
            <span>学生统计</span>
          </template>

          <div class="stats-overview">
            <div class="stat-item">
              <div class="stat-number">{{ studentStats.total_students || 0 }}</div>
              <div class="stat-label">总学生数</div>
            </div>
          </div>

          <el-divider />

          <div class="status-stats">
            <h4>学籍状态分布</h4>
            <div class="status-list">
              <div v-for="(count, status) in studentStats.by_status" :key="status" class="status-item">
                <span class="status-name">{{ getStatusText(status) }}:</span>
                <el-tag :type="getStatusType(status)">{{ count }} 人</el-tag>
              </div>
            </div>
          </div>

          <el-divider />

          <div class="employment-stats">
            <h4>就业状态分布</h4>
            <div class="employment-list">
              <div v-for="(count, status) in studentStats.by_employment" :key="status" class="employment-item">
                <span class="employment-name">{{ getEmploymentText(status) }}:</span>
                <el-tag :type="getEmploymentType(status)">{{ count }} 人</el-tag>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>

      <!-- 登录统计 -->
      <el-col :span="12">
        <el-card class="login-stats-card">
          <template #header>
            <span>登录统计</span>
          </template>

          <div class="stats-overview">
            <el-row :gutter="20">
              <el-col :span="8">
                <div class="stat-item">
                  <div class="stat-number">{{ loginStats.today_logins || 0 }}</div>
                  <div class="stat-label">今日登录</div>
                </div>
              </el-col>
              <el-col :span="8">
                <div class="stat-item">
                  <div class="stat-number">{{ loginStats.week_logins || 0 }}</div>
                  <div class="stat-label">本周登录</div>
                </div>
              </el-col>
              <el-col :span="8">
                <div class="stat-item">
                  <div class="stat-number">{{ loginStats.month_logins || 0 }}</div>
                  <div class="stat-label">本月登录</div>
                </div>
              </el-col>
            </el-row>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Refresh } from '@element-plus/icons-vue'
import { systemSettingsApi } from '@/api/system'

// 响应式数据
const loading = ref(false)
const systemInfo = ref<any>({})
const userStats = ref<any>({})
const studentStats = ref<any>({})
const loginStats = ref<any>({})

// 方法
const fetchSystemInfo = async () => {
  try {
    const response = await systemSettingsApi.getSystemInfo()
    // 检查响应结构
    if (response && response.data) {
      systemInfo.value = response.data
    } else if (response) {
      // 如果直接返回数据
      systemInfo.value = response
    } else {
      throw new Error('无效的响应数据')
    }
  } catch (error) {
    console.error('获取系统信息失败:', error)
    ElMessage.error(`获取系统信息失败: ${error.message || error}`)
    // 设置默认值以防止页面显示错误
    systemInfo.value = {
      application: { name: '鸥鹏超级面试官', version: '1.0.0', description: '智能面试管理系统' },
      system: { platform: '未知', python_version: '未知', django_version: '未知', debug_mode: false },
      database: { engine: '未知', name: '未知' }
    }
  }
}

const fetchUserStats = async () => {
  try {
    const response = await systemSettingsApi.getUserStatistics()
    // 检查响应结构
    if (response && response.data) {
      userStats.value = response.data
    } else if (response) {
      userStats.value = response
    } else {
      throw new Error('无效的响应数据')
    }
  } catch (error) {
    console.error('获取用户统计失败:', error)
    ElMessage.error('获取用户统计失败')
    // 设置默认值
    userStats.value = {
      total_users: 0,
      active_users: 0,
      inactive_users: 0,
      by_role: {}
    }
  }
}

const fetchStudentStats = async () => {
  try {
    const response = await systemSettingsApi.getStudentStatistics()
    // 检查响应结构
    if (response && response.data) {
      studentStats.value = response.data
    } else if (response) {
      studentStats.value = response
    } else {
      throw new Error('无效的响应数据')
    }
  } catch (error) {
    console.error('获取学生统计失败:', error)
    ElMessage.error('获取学生统计失败')
    // 设置默认值
    studentStats.value = {
      total_students: 0,
      by_status: {},
      by_employment: {},
      by_grade: {}
    }
  }
}

const fetchLoginStats = async () => {
  try {
    const response = await systemSettingsApi.getLoginStatistics()
    // 检查响应结构
    if (response && response.data) {
      loginStats.value = response.data
    } else if (response) {
      loginStats.value = response
    } else {
      throw new Error('无效的响应数据')
    }
  } catch (error) {
    console.error('获取登录统计失败:', error)
    ElMessage.error('获取登录统计失败')
    // 设置默认值
    loginStats.value = {
      today_logins: 0,
      week_logins: 0,
      month_logins: 0,
      daily_stats: []
    }
  }
}

const refreshSystemInfo = async () => {
  loading.value = true
  try {
    await fetchSystemInfo()
    ElMessage.success('系统信息刷新成功')
  } finally {
    loading.value = false
  }
}

const refreshAllData = async () => {
  loading.value = true
  try {
    await Promise.all([
      fetchSystemInfo(),
      fetchUserStats(),
      fetchStudentStats(),
      fetchLoginStats()
    ])
  } finally {
    loading.value = false
  }
}

// 工具方法
const getPythonVersion = () => {
  const version = systemInfo.value.system?.python_version
  if (!version) return '-'
  return version.split(' ')[0]
}

const getDatabaseEngine = () => {
  const engine = systemInfo.value.database?.engine
  if (!engine) return '-'
  if (engine.includes('sqlite')) return 'SQLite'
  if (engine.includes('postgresql')) return 'PostgreSQL'
  if (engine.includes('mysql')) return 'MySQL'
  return engine
}

const getRoleText = (role: string) => {
  const textMap: any = {
    'admin': '管理员',
    'teacher': '老师',
    'student': '学生'
  }
  return textMap[role] || role
}

const getRoleType = (role: string) => {
  const typeMap: any = {
    'admin': 'danger',
    'teacher': 'warning',
    'student': 'primary'
  }
  return typeMap[role] || 'info'
}

const getStatusText = (status: string) => {
  const textMap: any = {
    'active': '在校',
    'graduated': '已毕业',
    'suspended': '休学',
    'dropped': '退学'
  }
  return textMap[status] || status
}

const getStatusType = (status: string) => {
  const typeMap: any = {
    'active': 'success',
    'graduated': 'primary',
    'suspended': 'warning',
    'dropped': 'danger'
  }
  return typeMap[status] || 'info'
}

const getEmploymentText = (status: string) => {
  const textMap: any = {
    'unemployed': '未就业',
    'employed': '已就业',
    'self_employed': '自主创业',
    'further_study': '继续深造'
  }
  return textMap[status] || status
}

const getEmploymentType = (status: string) => {
  const typeMap: any = {
    'unemployed': 'warning',
    'employed': 'success',
    'self_employed': 'primary',
    'further_study': 'info'
  }
  return typeMap[status] || 'info'
}

// 生命周期
onMounted(() => {
  refreshAllData()
})
</script>

<style scoped>
.system-settings {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.info-section h4 {
  margin: 0 0 15px 0;
  color: #409eff;
  font-size: 16px;
}

.info-list {
  margin-bottom: 20px;
}

.info-item {
  display: flex;
  justify-content: space-between;
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
}

.info-item:last-child {
  border-bottom: none;
}

.label {
  color: #909399;
  font-weight: 500;
}

.value {
  color: #303133;
}

.stats-overview {
  margin-bottom: 20px;
}

.stat-item {
  text-align: center;
  padding: 20px 0;
}

.stat-number {
  font-size: 28px;
  font-weight: bold;
  color: #409eff;
  margin-bottom: 8px;
}

.stat-label {
  color: #909399;
  font-size: 14px;
}

.role-stats h4,
.status-stats h4,
.employment-stats h4 {
  margin: 0 0 15px 0;
  color: #409eff;
  font-size: 16px;
}

.role-list,
.status-list,
.employment-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.role-item,
.status-item,
.employment-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 12px;
  background-color: #f8f9fa;
  border-radius: 4px;
}

.role-name,
.status-name,
.employment-name {
  color: #606266;
  font-weight: 500;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .system-settings {
    padding: 10px;
  }

  .el-col {
    margin-bottom: 20px;
  }

  .stat-item {
    padding: 15px 0 !important;
  }

  .stat-number {
    font-size: 24px !important;
  }

  .info-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 4px;
  }
}
</style>